#include "StdAfx.h"
#include "TcpConnection.h"
#include "Robot.h"

namespace RobotCollisionDetection
{
	void TcpConnection::Listen(Object^ params)
	{
		try
		{
			// retrieve parameters
			array<Object^>^ parameters = (array<Object^>^)params;
			IPAddress^ localAddr = IPAddress::Parse( (String^)parameters[0] );
			Int32 port = (Int32)parameters[1];

			// TcpListener* server = new TcpListener(port);
			TcpListener^ server = gcnew TcpListener( localAddr,port );

			// Start listening for client requests.
			server->Start();

			// Buffer for reading data
			array<Byte>^bytes = gcnew array<Byte>(256);
			String^ data = nullptr;

			// Enter the listening loop.
			while ( true )
			{
				try
				{
					Console::Write( "Waiting for a connection... " );

					// Perform a blocking call to accept requests.
					// You could also user server.AcceptSocket() here.
					TcpClient^ client = server->AcceptTcpClient();
					Console::WriteLine( "Connected!" );
					data = nullptr;

					// Get a stream Object* for reading and writing
					NetworkStream^ stream = client->GetStream();
					Int32 i;

					// Loop to receive all the data sent by the client.
					while ( i = stream->Read( bytes, 0, bytes->Length ) )
					{
						/*
						// Translate data bytes to a ASCII String*.
						data = Text::Encoding::ASCII->GetString( bytes, 0, i );
						Console::WriteLine( "Received: {0}", data );

						// Process the data sent by the client.
						data = data->ToUpper();
						array<Byte>^msg = Text::Encoding::ASCII->GetBytes( data );
						*/
						if (kawasaki!=nullptr)
							kawasaki->PositionsBuffer[(rand()%5)+1]+=(rand()%10)-5;

						if (mitsubishi!=nullptr)
							mitsubishi->PositionsBuffer[(rand()%5)+1]+=(rand()%10)-5;
					}

					Thread::Sleep(125);
				}
				catch ( IOException^ e)
				{
					Console::WriteLine( "IOException: {0}", e );
				}
			}
		}
		catch ( SocketException^ e ) 
		{
			Console::WriteLine( "SocketException: {0}", e );
		}
	}
}
